package com.linxin.ai_automates_periodontal_treatment_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxin.ai_automates_periodontal_treatment_system.common.Result;
import com.linxin.ai_automates_periodontal_treatment_system.entity.*;
import com.linxin.ai_automates_periodontal_treatment_system.service.DiagnosticRecordService;
import com.linxin.ai_automates_periodontal_treatment_system.service.DiseaseHistoryService;
import com.linxin.ai_automates_periodontal_treatment_system.service.PatientService;
import com.linxin.ai_automates_periodontal_treatment_system.service.SystemicDiseaseRecordService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/patient")
public class PatientController {
    @Autowired
    private PatientService patientService; // 注入患者服务
    @Autowired
    private DiseaseHistoryService diseaseHistoryService; // 注入疾病历史服务
    @Autowired
    private SystemicDiseaseRecordService systemicDiseaseRecordService; // 注入全身病理服务
    @Autowired
    private DiagnosticRecordService diagnosticRecordService; // 注入诊断记录服务

    /**
     * 获取患者列表
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("getPatientList")
    public Result<Page<Patient>> getPatientList(
            @RequestParam(value = "pageNum", required = true) Integer pageNum,
            @RequestParam(value = "pageSize", required = true) Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "gender", required = false) Character gender,
            HttpServletRequest request
    ) {
        // 1. 获取当前的doctorId
        Integer doctorId = (Integer) request.getAttribute("doctorId");

        // 2.创建分页查询对象
        Page<Patient> page = new Page<>(pageNum, pageSize);

        // 3. 创建查询条件
        LambdaQueryWrapper<Patient> queryWrapper = new LambdaQueryWrapper<>();

        // 4. 根据名字模糊查询
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like(Patient::getName, name);
        }

        if (gender != null) {
            queryWrapper.eq(Patient::getGender, gender);
        }

        // 5. 根据doctorId查询
        queryWrapper.eq(Patient::getDoctorId, doctorId);

        // 6. 根据创建时间倒序排序
        queryWrapper.orderByDesc(Patient::getCreateTime).orderByDesc(Patient::getId);

        // 6. 执行查询
        patientService.page(page, queryWrapper);

        // 7. 返回查询结果
        return Result.success(page);
    }


    /**
     * 添加患者信息
     *
     * @param patient
     * @param request
     * @return
     */
    @PostMapping("addPatient")
    public Result<String> addPatient(@RequestBody Patient patient, HttpServletRequest request) {
        // 1. 获取当前的doctorId
        Integer doctorId = (Integer) request.getAttribute("doctorId");

        // 2. 设置doctorId
        patient.setDoctorId(doctorId);

        // 3. 设置创建时间, 更新时间
        patient.setCreateTime(LocalDateTime.now());
        patient.setUpdateTime(LocalDateTime.now());

        // 4. 保存患者信息
        patientService.save(patient);

        return Result.success("添加患者成功");
    }

    /**
     * 编辑患者信息
     *
     * @param patient
     * @param request
     * @return
     */
    @PostMapping("editPatient")
    public Result<String> editPatient(@RequestBody Patient patient, HttpServletRequest request) {
        // log.info("editPatient: {}", patient);
        // 1. 获取当前的doctorId
        Integer doctorId = (Integer) request.getAttribute("doctorId");

        // 2. 设置doctorId
        patient.setDoctorId(doctorId);

        // 3. 设置更新时间
        patient.setUpdateTime(LocalDateTime.now());

        // 4. 更新患者信息
        patientService.updateById(patient);

        return Result.success("修改患者成功");
    }

    /**
     * 获取患者信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("getPatientInfo/{id}")
    public Result<Patient> getPatientInfo(@PathVariable Integer id, HttpServletRequest request) {
//         log.info("getPatientInfo: {}", id);

        // 1. 获取当前的doctorId
        Integer doctorId = (Integer) request.getAttribute("doctorId");

        // 2. 根据患者id和doctorId查询患者信息

        Patient patient = patientService.getOne(new LambdaQueryWrapper<Patient>()
                .eq(Patient::getId, id)
                .eq(Patient::getDoctorId, doctorId));

        // 3. 返回查询结果
        return Result.success(patient);
    }

    /**
     * 根据患者id和记录id获取患者病史信息
     *
     * @param patientId
     * @param recordId
     * @return
     */
    @GetMapping("getDiseaseHistory/{patientId}/{recordId}")
    public Result<DiseaseHistory> getDiseaseHistory(@PathVariable Integer patientId, @PathVariable Integer recordId) {
//        log.info("getDiseaseHistory: patientId: {}, recordId: {}", patientId, recordId);
        // 1. 根据patientId和recordId查询病史信息
        DiseaseHistory diseaseHistory = diseaseHistoryService.getOne(new LambdaQueryWrapper<DiseaseHistory>()
                .eq(DiseaseHistory::getPatientId, patientId)
                .eq(DiseaseHistory::getRecordId, recordId));

//        log.info("getDiseaseHistory: {}", diseaseHistory);
        return Result.success(diseaseHistory);
    }

    /**
     * 据患者id和记录id获取获取全身状况表
     *
     * @param patientId
     * @param recordId
     * @return
     */
    @GetMapping("getSystemicDisease/{patientId}/{recordId}")
    public Result<SystemicDiseaseRecord> getSystemicDisease(@PathVariable Integer patientId, @PathVariable Integer recordId) {
        // log.info("getSystemicDisease: patientId: {}, recordId: {}", patientId, recordId);
        // 1. 根据patientId和recordId查询全身病理信息
        SystemicDiseaseRecord systemicDiseaseRecord = systemicDiseaseRecordService.getOne(new LambdaQueryWrapper<SystemicDiseaseRecord>()
                .eq(SystemicDiseaseRecord::getPatientId, patientId)
                .eq(SystemicDiseaseRecord::getRecordId, recordId));

        // log.info("getSystemicDisease: {}", systemicDiseaseRecord);
        return Result.success(systemicDiseaseRecord);
    }

    /**
     * 更新病史信息
     *
     * @param diseaseHistory
     * @return
     */
    @PostMapping("/editDiseaseHistory")
    public Result<String> editDiseaseHistory(@RequestBody DiseaseHistory diseaseHistory) {
//         log.info("editDiseaseHistory: {}", diseaseHistory);
        // 1. 更新病史信息
        diseaseHistoryService.updateById(diseaseHistory);
        return Result.success("更新病史信息成功");
    }

    /**
     * 更新 全身病理信息
     *
     * @param systemicDiseaseRecord
     * @return
     */
    @PostMapping("/editSystemicDisease")
    public Result<String> editSystemicDisease(@RequestBody SystemicDiseaseRecord systemicDiseaseRecord) {
        log.info("editSystemicDisease: {}", systemicDiseaseRecord);

        // 1. 更新全身病理信息
        systemicDiseaseRecordService.updateById(systemicDiseaseRecord);
        return Result.success("更新全身病理信息成功");
    }


    /**
     * 根据id删除患者信息
     */
    @DeleteMapping("/deletePatient/{id}")
    public Result<String> deletePatient(@PathVariable Integer id) {
        // log.info("deletePatient: {}", id);
        // 1. 根据id删除患者信息
        patientService.removeById(id);
        // 2. 根据患者id删除病史信息
        diseaseHistoryService.remove(new LambdaQueryWrapper<DiseaseHistory>()
               .eq(DiseaseHistory::getPatientId, id));
        // 3. 根据患者id删除全身病理信息
        systemicDiseaseRecordService.remove(new LambdaQueryWrapper<SystemicDiseaseRecord>()
               .eq(SystemicDiseaseRecord::getPatientId, id));
        // 4. 根据患者id删除诊断信息
        diagnosticRecordService.remove(new LambdaQueryWrapper<DiagnosticRecord>()
               .eq(DiagnosticRecord::getPatientId, id));

        return Result.success("删除患者信息成功");
    }

    // 更新患者的类型
    @PutMapping("/updatePatientClassify/{patientId}/{patientClassifyId}")
    public Result<String> updatePatientClassify(@PathVariable Integer patientId,
                                                @PathVariable Integer patientClassifyId) {
        // 1. 根据患者id获取患者信息
        Patient patient = patientService.getById(patientId);
        // 2. 设置患者的类型
        patient.setPatientClassifyId(patientClassifyId);
        // 3. 更新患者信息
        patientService.updateById(patient);

        return Result.success("更新患者类型成功");
    }

}
